package com.ruoyi.platform.system.user.service;

import com.ruoyi.base.constant.Constants;
import com.ruoyi.base.enums.ExceptionEnum;
import com.ruoyi.base.exception.SysException;
import com.ruoyi.base.permission.TokenManager;
import com.ruoyi.base.redis.login.PwdWrongTimesRedis;
import com.ruoyi.base.service.BaseService;
import com.ruoyi.base.utils.inputcheck.InputCheckUtils;
import com.ruoyi.base.utils.md5.Md5Utils;
import com.ruoyi.platform.system.user.dao.UserDAO;
import com.ruoyi.platform.system.user.enums.UserAccountStatusEnum;
import com.ruoyi.platform.system.user.pojo.LoginUserDTO;
import com.ruoyi.platform.system.user.pojo.UserDO;
import com.ruoyi.platform.system.verify.manager.VerifyCodeManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 登录
 * @author lcf
 */
@Service
public class LoginService extends BaseService {
    @Autowired
    private UserDAO sysUserDao;
    @Autowired
    private TokenManager tokenService;
    @Autowired
    private VerifyCodeManager verifyCodeManager;
    @Autowired
    private PwdWrongTimesRedis pwdWrongTimesRedis;

    /**
     * 登录
     *
     * @param account  用户名
     * @param password 密码
     * @return token
     */
    public String login(String account, String password, String verifyKey, String verifyCode) {
        //检查密码合法性
        InputCheckUtils.checkPwd(password);
        //是否需要检查验证码
        if (pwdWrongTimesRedis.isNeedVerifyCode()) {
            if (StringUtils.isBlank(verifyCode)) {
                throw exception(ExceptionEnum.VERIFY_CODE_EMPTY);
            }
            //检查验证码
            verifyCodeManager.checkVerifyCode(verifyKey, verifyCode);
        }

        //检查登录
        UserDO user = sysUserDao.getByAccount(account);
        if (user == null) {
            user = sysUserDao.getByPhone(account);
        }

        //检查账号密码
        if (user == null || !Md5Utils.matchesPassword(password, user.getPassword())) {
            pwdWrongTimesRedis.cache();
            throw exception(ExceptionEnum.ACCOUNT_OR_PWD_WRONG);
        }

        //如果是初始密码则强制要求修改密码
        if (Md5Utils.matchesPassword(Constants.DEFAULT_PASSWORD, user.getPassword())) {
            throw exception(ExceptionEnum.PLEASE_EDIT_PWD);
        }

        //检查账号状态
        if (Objects.equals(UserAccountStatusEnum.DISABLE.getCode(), user.getAccountStatus())) {
            throw new SysException(ExceptionEnum.ACCOUNT_HAS_STOP);
        }

        return tokenService.createToken(new LoginUserDTO(user));
    }

    /**
     * 退出登录
     */
    public void logout() {
        LoginUserDTO loginUser = tokenService.getLoginUser();
        if (loginUser != null) {
            // 删除用户信息缓存
            tokenService.delLoginUser(loginUser.getToken());
            //删除登录密码错误次数缓存
            pwdWrongTimesRedis.delCache();
        }
    }
}
